package com.copsoftware.mantenimientos.acusado.service;

import java.util.ArrayList;
import java.util.Collection;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.beans.BeanUtils;

import com.copsoftware.entity.DenAcusadoImpl;
import com.copsoftware.hibernate.cfg.HibernateUtils;
import com.copsoftware.mantenimientos.acusado.beans.Acusado;
import com.copsoftware.mantenimientos.acusado.dao.AcusadoDAO;

public class AcusadoService {

	public void guardarAcusado(Acusado acusado) throws Exception {
		DenAcusadoImpl denAcusado = getAcusado(acusado.getCPersona());
		
		BeanUtils.copyProperties(acusado, denAcusado);
		
		Session session = HibernateUtils.getSessionFactory()
		.getCurrentSession();
		Transaction tx = null;
	
		try {
			tx = session.beginTransaction();
			AcusadoDAO acusadoDAO = new AcusadoDAO();
			acusadoDAO.setSession(session);
			acusadoDAO.guardarAcusado(denAcusado);
			
			tx.commit();
			
			BeanUtils.copyProperties(denAcusado, acusado);
		}catch (Exception e) {
			// TODO Auto-generated catch block
			tx.rollback();
		}
	}
	
	private DenAcusadoImpl getAcusado(Integer cAcusado) {
		DenAcusadoImpl denAcusado = null;
		if (cAcusado == null) {
			denAcusado = new DenAcusadoImpl();
		} else {
			denAcusado = buscarAcusado(cAcusado);
		}
		return denAcusado;
	}
	
	private DenAcusadoImpl buscarAcusado(Integer cAcusado) {

		Session session = HibernateUtils.getSessionFactory()
				.getCurrentSession();
		Transaction tx = null;
		DenAcusadoImpl acusado = null;
		try {
			tx = session.beginTransaction();
			AcusadoDAO acusadoDAO = new AcusadoDAO();
			acusadoDAO.setSession(session);
			acusado = acusadoDAO.buscarAcusado(cAcusado);
			tx.commit();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			tx.rollback();
		}
		return acusado;

	}
	
	public void buscarAcusado(Acusado acusado)
	{
		DenAcusadoImpl denAcusado = getAcusado(acusado.getCPersona());
		BeanUtils.copyProperties(denAcusado, acusado);
	}
	
	public Collection buscarDelitosAcusado (Integer cAcusado)
	{
		Session session = HibernateUtils.getSessionFactory()
		.getCurrentSession();
		Transaction tx = null;
		Collection acusados = new ArrayList();
		try {
			tx = session.beginTransaction();
			AcusadoDAO acusadoDAO = new AcusadoDAO();
			acusadoDAO.setSession(session);
			acusados = acusadoDAO.buscarDelitoConAcusado(cAcusado);
			tx.commit();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			tx.rollback();
		}
		return acusados;
	}
	
}
